/**
 * 
 */
package com.ls.lserp.modules.sys.utils;

import java.awt.geom.Area;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.utils.CacheUtils;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.SendMailUtil;
import com.ls.lserp.common.utils.SpringContextHolder;
import com.ls.lserp.dbaccess.Entity.MailMessage;
import com.ls.lserp.modules.order.entity.CustomizationContract;
import com.ls.lserp.modules.sys.dao.MenuDao;
import com.ls.lserp.modules.sys.dao.RoleDao;
import com.ls.lserp.modules.sys.dao.UserDao;
import com.ls.lserp.modules.sys.entity.Menu;
import com.ls.lserp.modules.sys.entity.Role;
import com.ls.lserp.modules.sys.entity.SendEmailMessage;
import com.ls.lserp.modules.sys.entity.Shop;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.security.SystemAuthorizingRealm.Principal;

/**
 * 用户工具类
 * @author 
 * @version 2013-12-05
 */
public class UserUtils {

	private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
	private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
	private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
	/*private static AreaDao areaDao = SpringContextHolder.getBean(AreaDao.class);
	private static OfficeDao officeDao = SpringContextHolder.getBean(OfficeDao.class);*/

	public static final String USER_CACHE = "userCache";
	public static final String USER_CACHE_ID_ = "id_";
	public static final String USER_CACHE_LOGIN_NAME_ = "ln";
	public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_";

	public static final String CACHE_ROLE_LIST = "roleList";
	public static final String CACHE_MENU_LIST = "menuList";
	public static final String CACHE_MENU_ALL_LIST = "menuAllList";
	public static final String CACHE_AREA_LIST = "areaList";
	public static final String CACHE_OFFICE_LIST = "officeList";
	public static final String CACHE_OFFICE_ALL_LIST = "officeAllList";
	
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static User get(Long id){
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
		if (user ==  null){
			user = userDao.get(id);
			if (user == null){
				return null;
			}
			user.setRoleList(roleDao.findListByUser(new Role(user)));
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}
	
	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return 取不到返回null
	 */
	public static User getByLoginName(String loginName){
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName);
		if (user == null){
			user = userDao.getByLoginName(new User(null, loginName));
			if (user == null){
				return null;
			}
			user.setRoleList(roleDao.findListByUser(new Role(user)));
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}
	
	/**
	 * 清除当前用户缓存
	 */
	public static void clearCache(){
		removeCache(CACHE_ROLE_LIST);
		removeCache(CACHE_MENU_LIST);
		removeCache(CACHE_MENU_ALL_LIST);
		removeCache(CACHE_AREA_LIST);
		removeCache(CACHE_OFFICE_LIST);
		removeCache(CACHE_OFFICE_ALL_LIST);
		UserUtils.clearCache(getUser());
	}
	
	/**
	 * 清除指定用户缓存
	 * @param user
	 */
	public static void clearCache(User user){
		CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName());
//		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getOldLoginName());
//		if (user.getOffice() != null && user.getOffice().getId() != null){
//			CacheUtils.remove(USER_CACHE, USER_CACHE_LIST_BY_OFFICE_ID_ + user.getOffice().getId());
//		}
	}
	
	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public static User getUser(){
		Principal principal = getPrincipal();
		if (principal!=null){
			User user = get(principal.getId());
			if (user != null){
//			    User u=userDao.findUserShop(user);
//			    Shop shop=new Shop();
//			    if(u==null|| u.getShop()==null){
//			        shop.setId(-1L);
//                    shop.setShopName("");
//                    shop.setShopCode("");
//			    }else{
//			        shop.setId(u.getShop().getId());
//	                shop.setShopName(u.getShop().getShopName());
//	                shop.setShopCode(u.getShop().getShopCode());
//			    }
//			  
//			    user.setShop(shop);
				
			    return user;
			}
			user = new User();
			user.setId(1L);
			return user;
		}
		// 如果没有登录，则返回实例化空的User对象，默认UserAdmin用户ID。
		User user = new User();
		user.setId(1L);
		return user;
	}
	
	/**
     * 发送邮件
     * @param sendEmailMessage
     * @throws Exception
     */
    public static void sendEmail(SendEmailMessage sendEmailMessage) throws Exception {
        //主题
        String mailTheme = sendEmailMessage.getDataTheme();
        if (mailTheme.indexOf("YYYYMMDD01") != -1) {
        	mailTheme = mailTheme.replace("YYYYMMDD01", sendEmailMessage.getDataYYMMDD01());
        }
        if (mailTheme.indexOf("XXX02") != -1) {
        	mailTheme = mailTheme.replace("XXX02", sendEmailMessage.getDataXXX02());
        }
        //正文
        String mailMessage = sendEmailMessage.getDataMessage();
        if (mailMessage.indexOf("XXX01") != -1) {
        	mailMessage =  mailMessage.replace("XXX01", UserUtils.getUser().getFirstName()+UserUtils.getUser().getLastName());
		}
        if (mailMessage.indexOf("XXX02") != -1) {
        	mailMessage =  mailMessage.replace("XXX02", sendEmailMessage.getDataXXX02());
        }
        if (mailMessage.indexOf("XXX03") != -1) {
        	mailMessage =  mailMessage.replace("XXX03", sendEmailMessage.getDataXXX03());
        }
        if (mailMessage.indexOf("XXX04") != -1) {
        	mailMessage =  mailMessage.replace("XXX04", sendEmailMessage.getDataXXX04());
        }
        if (mailMessage.indexOf("XXX05") != -1) {
        	mailMessage =  mailMessage.replace("XXX05", sendEmailMessage.getDataXXX05());
        }
        if (mailMessage.indexOf("XXX06") != -1) {
        	mailMessage =  mailMessage.replace("XXX06", sendEmailMessage.getDataXXX06());
        }
        if (mailMessage.indexOf("XXX07") != -1) {
        	mailMessage =  mailMessage.replace("XXX07", sendEmailMessage.getDataXXX07());
        }
        if (mailMessage.indexOf("XXX08") != -1) {
        	mailMessage =  mailMessage.replace("XXX08", sendEmailMessage.getDataXXX08());
        }
        if (mailMessage.indexOf("XXX09") != -1) {
        	mailMessage =  mailMessage.replace("XXX09", sendEmailMessage.getDataXXX09());
        }
        if (mailMessage.indexOf("YYYYMMDD02") != -1) {
        	mailMessage =  mailMessage.replace("YYYYMMDD02", sendEmailMessage.getDataYYMMDD02());
        }
        if (mailMessage.indexOf("XURLX") != -1) {
        	mailMessage =  mailMessage.replace("XURLX", "<br><a href='" + sendEmailMessage.getDataXURLX() + "'>" + sendEmailMessage.getDataXURLX() + "</a>");
        }
        //发送
        if ("qualityControl".equals(sendEmailMessage.getMailFlag())) {
        	//质检主管
        	List<User> uList = userDao.getChargeUser(22L);
			if (uList != null && uList.size() > 0) {
				for (int i = 0; i < uList.size(); i++) {
					SendMailUtil.sendCommonMail(uList.get(i).getEmail(), mailTheme, mailMessage);
					//保存邮件
					saveEmail(uList.get(i).getId(),mailTheme,sendEmailMessage.getDataXURLX());
				}
			}
		}else if ("materialAlert".equals(sendEmailMessage.getMailFlag())) {
        	//仓储主管
			List<User> uList = userDao.getChargeUser(21L);
			if (uList != null && uList.size() > 0) {
				for (int i = 0; i < uList.size(); i++) {
					SendMailUtil.sendCommonMail(uList.get(i).getEmail(), mailTheme, mailMessage);
					//保存邮件
					saveEmail(uList.get(i).getId(),mailTheme,sendEmailMessage.getDataXURLX());
				}
			}
			//仓储员工
			List<User> uList_S = userDao.getChargeUser(27L);
			if (uList_S != null && uList_S.size() > 0) {
				for (int i = 0; i < uList_S.size(); i++) {
					SendMailUtil.sendCommonMail(uList_S.get(i).getEmail(), mailTheme, mailMessage);
					//保存邮件
					saveEmail(uList_S.get(i).getId(),mailTheme,sendEmailMessage.getDataXURLX());
				}
			}
		}else {
			//获取用户部门负责人
			List<User> uList = userDao.findChargeUser(getUser().getId());
	        if (uList != null && uList.size() > 0) {
				for (int i = 0; i < uList.size(); i++) {
					SendMailUtil.sendCommonMail(uList.get(i).getEmail(), mailTheme, mailMessage);
	        		//保存邮件
					saveEmail(uList.get(i).getId(),mailTheme,sendEmailMessage.getDataXURLX());
				}
			}
		}
        //获取公司负责人
        List<User> uComList = userDao.findComChargeUser();
        if (uComList != null && uComList.size() > 0) {
			for (int i = 0; i < uComList.size(); i++) {
				SendMailUtil.sendCommonMail(uComList.get(i).getEmail(), mailTheme, mailMessage);
      		//保存邮件
				saveEmail(uComList.get(i).getId(),mailTheme,sendEmailMessage.getDataXURLX());
			}
		}
        //系统主管
		List<User> adminList = userDao.getChargeUser(1L);
		if (adminList != null && adminList.size() > 0) {
			for (int i = 0; i < adminList.size(); i++) {
				SendMailUtil.sendCommonMail(adminList.get(i).getEmail(), mailTheme, mailMessage);
				//保存邮件
				saveEmail(adminList.get(i).getId(),mailTheme,sendEmailMessage.getDataXURLX());
			}
		}
        //固定给某某某发送邮件
        SendMailUtil.sendCommonMail(ResourcesUtil.getConfig("shaoyun.tan"), mailTheme, mailMessage);
    }
    /**
     * 保存邮件
     * @param sendEmailMessage
     * @throws Exception
     */
    public static void saveEmail(long userId,String mailTheme, String url) throws Exception {
    	MailMessage mail = new MailMessage();
    	//收信人
    	mail.setReceiveUser(userId);
    	//主题
    	mail.setContent(mailTheme);
    	//URL
    	mail.setUrl(url);
    	if (UserUtils.getUser().getId() != null) {
    		mail.setCreateUser(UserUtils.getUser().getId());
		}else {
			mail.setCreateUser(1);
		}
    	userDao.insertMailMessage(mail);
    }
	/**
	 * 获取当前用户角色列表
	 * @return
	 */
	public static List<Role> getRoleList(){
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
		if (roleList == null){
			User user = getUser();
			if (user.isAdmin()){
				roleList = roleDao.findAllList(new Role());
			}else{
				/*Role role = new Role();
				role.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "u"));
				roleList = roleDao.findListByUser(role);*/
			    roleList = roleDao.findAllList(new Role());
			}
			putCache(CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}
	
	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static List<Menu> getMenuList(){
		@SuppressWarnings("unchecked")
    	List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
		if (menuList == null){
			User user = getUser();
			if (user.isAdmin()){
			    Menu menu=new Menu();
			    menu.setMenuNotShow(ResourcesUtil.getConfig("menu_admin_not_show"));
				menuList = menuDao.findAdminList(menu);
			}else{
				Menu m = new Menu();
				m.setUserId(user.getId());
				menuList = menuDao.findByUserId(m);
			}
			putCache(CACHE_MENU_LIST, menuList);
		}
		return menuList;
	}
	
	   /**
     * 获取当前用户授权菜单
     * @return
     */
    public static List<Menu> getMenuAllList(){
        @SuppressWarnings("unchecked")
        List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_ALL_LIST);
        if (menuList == null){
            menuList = menuDao.findAllList(new Menu());
            putCache(CACHE_MENU_ALL_LIST, menuList);
        }
        return menuList;
    }
	
	/**
	 * 获取当前用户授权的区域
	 * @return
	 */
	public static List<Area> getAreaList(){
		@SuppressWarnings("unchecked")
		List<Area> areaList = (List<Area>)getCache(CACHE_AREA_LIST);
//		if (areaList == null){
//			areaList = areaDao.findAllList(new Area());
//			putCache(CACHE_AREA_LIST, areaList);
//		}
		return areaList;
	}
	
	/**
	 * 获取当前用户有权限访问的部门
	 * @return
	 */
	/*public static List<Office> getOfficeList(){
		@SuppressWarnings("unchecked")
		List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_LIST);
		if (officeList == null){
			User user = getUser();
			if (user.isAdmin()){
				officeList = officeDao.findAllList(new Office());
			}else{
				Office office = new Office();
				office.getSqlMap().put("dsf", BaseService.dataScopeFilter(user, "a", ""));
				officeList = officeDao.findList(office);
			}
			putCache(CACHE_OFFICE_LIST, officeList);
		}
		return officeList;
	}*/

	/**
	 * 获取当前用户有权限访问的部门
	 * @return
	 */
	/*public static List<Office> getOfficeAllList(){
		@SuppressWarnings("unchecked")
		List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_ALL_LIST);
		if (officeList == null){
			officeList = officeDao.findAllList(new Office());
		}
		return officeList;
	}
	*/
	/**
	 * 获取授权主要对象
	 */
	public static Subject getSubject(){
		return SecurityUtils.getSubject();
	}
	
	/**
	 * 获取当前登录者对象
	 */
	public static Principal getPrincipal(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal)subject.getPrincipal();
			if (principal != null){
				return principal;
			}
//			subject.logout();
		}catch (UnavailableSecurityManagerException e) {
			
		}catch (InvalidSessionException e){
			
		}
		return null;
	}
	
	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
//			subject.logout();
		}catch (InvalidSessionException e){
			
		}
		return null;
	}
	
	// ============== User Cache ==============
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
//		Object obj = getCacheMap().get(key);
		Object obj = getSession().getAttribute(key);
		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
		getSession().setAttribute(key, value);
	}

	public static void removeCache(String key) {
//		getCacheMap().remove(key);
		getSession().removeAttribute(key);
	}
	
//	public static Map<String, Object> getCacheMap(){
//		Principal principal = getPrincipal();
//		if(principal!=null){
//			return principal.getCacheMap();
//		}
//		return new HashMap<String, Object>();
//	}
	
	public static Boolean isShopUser(){
	    
	    Long shopId=getUser().getShop().getId();
	    if(shopId!=null &&!"-1".equals(String.valueOf(shopId))) {
	        return true;
	    }else{
	        return false;
	    }
	}
	
}
